package com.mutouren.modules.organize.service.impl;

import java.util.List;

import com.mutouren.common.entity.ValidState;
import com.mutouren.common.orm.Transcation;
import com.mutouren.common.orm.TranscationFactory;
import com.mutouren.modules.organize.dao.OrgDaoManager;
import com.mutouren.modules.organize.dao.RoleDao;
import com.mutouren.modules.organize.dao.RoleFunctionDao;
import com.mutouren.modules.organize.model.Function;
import com.mutouren.modules.organize.model.Role;
import com.mutouren.modules.organize.model.RoleFunction;
import com.mutouren.modules.organize.service.RoleService;

public class RoleServiceImpl implements RoleService {
	
	private static RoleDao roleDao;
	private static RoleFunctionDao roleFunctionDao;

	static {
		roleDao = OrgDaoManager.getOrgDaoFactory().getRoleDao();
		roleFunctionDao = OrgDaoManager.getOrgDaoFactory().getRoleFunctionDao();		
	}		

	@Override
	public Role get(int id) {
		return roleDao.get(id);
	}

	@Override
	public void save(Role role) {
		roleDao.save(role);
	}

	@Override
	public int update(Role role) {
		return roleDao.update(role);
	}

	@Override
	public int setValidState(int id, ValidState validState) {
		return roleDao.setValidState(id, validState.value);
	}

	@Override
	public void setFunctions(int roleId, List<Integer> listFuncId) {		
		Transcation trans = TranscationFactory.createTranscation();
		try {
			trans.begin();
			roleFunctionDao.deleteByRoleID(roleId, trans);
			for(Integer funcId : listFuncId) {
				roleFunctionDao.save(new RoleFunction(roleId, funcId), trans);
			}
			trans.commit();
		} catch(RuntimeException ex) {
			trans.rollback();
			throw ex;
		} finally {
			trans.close();
		}	
	}

	@Override
	public List<Function> getFunctions(int roleId) {
		return roleFunctionDao.getFunctionsByRoleId(roleId);
	}

	@Override
	public List<Role> findRoles() {
		return roleDao.findRoles();
	}

}
